package com.qianbei.view.transport;

import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetRecord;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.common.utilis.img.CanmlTools;
import com.qianbei.common.utilis.img.ImageTools;
import com.qianbei.common.view.NoScrollListView;
import com.qianbei.view.bluetooth.BluetoothService;
import com.qianbei.view.bluetooth.Const;
import com.qianbei.view.bluetooth.DeviceScanActivity;
import com.qianbei.view.bluetooth.Utils;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.util.TextUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hand.blelib.BleBus;
import cn.hand.blelib.HDModelData;

public class RecordweightActivity2 extends BaseActivity implements CanmlTools.CamerCallback {

    private static final String TAG = "RecordweightActivity2";
    TextView ts_company;
    TextView ts_address;
    TextView contactPerson;
    TextView contactPhone;
    TextView empty_big_box;
    TextView empty_small_box;
    TextView full_small_box;
    TextView full_big_box;
    @Bind(R.id.up_img)
    TextView up_img;

    @Bind(R.id.record_save)
    TextView record_save;

    @Bind(R.id.show_img)
    ImageView show_img;
    /**
     * 当前收运客户
     */
    TrasportBean.ArrayBean.CustomerAryBean c;
    @Bind(R.id.about_question_list_view)
    NoScrollListView mAboutQuestionListView;

    private RecorWeightAdapter mAboutQuestionAdapter;
    EditText allWeightEt;
    EditText noBoxWeightEt;

    private CanmlTools canmlTools = null;

    /**
     * 上传图片的ID
     */
    String ID;
    String NAME;
    Map<String, String> fileParams = new HashMap<>();
    String allWeight;
    List<TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean> list;

    float noBoxWeightVlaue = 0;
    private String msgSp;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_record_weight_activity2);
        sp = getSharedPreferences(TextUtil.shhc_gfwl_sp, Context.MODE_PRIVATE);
        //绑定activity
        ButterKnife.bind(this);
        setTitle("录入重量");
        BleBus.getDefault().initBleBus(MyApplication.mApplication);  //在显示页面初始化
        Bundle b = getIntent().getExtras();
        c = (TrasportBean.ArrayBean.CustomerAryBean) b.get("key");
        ts_company = (TextView) findViewById(R.id.ts_company);
        ts_address = (TextView) findViewById(R.id.ts_address);
        contactPerson = (TextView) findViewById(R.id.contactPerson);
        contactPhone = (TextView) findViewById(R.id.contactPhone);
        empty_big_box = (TextView) findViewById(R.id.empty_big_box);
        empty_small_box = (TextView) findViewById(R.id.empty_small_count);
        full_small_box = (TextView) findViewById(R.id.full_small_box);
        full_big_box = (TextView) findViewById(R.id.full_big_box);

        ts_company.setText(c.getCustomerName());
        ts_address.setText(c.getAddress());
        contactPerson.setText(c.getContactPerson());
        contactPhone.setText(c.getContactPhone());
        list = c.getNeedWeight();
        //Log.d("测试数据", "数据:"+list.get(0).getName());
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean ebb = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        ebb.setName("大号空箱");
//        ebb.setValue(b.getString("empty_big_box")==null?"":b.getString("empty_big_box"));
        ebb.setValue("0");
        ebb.setHint("个                            ");
        list.add(ebb);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean esb = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        esb.setName("小号空箱");
//        esb.setValue(b.getString("empty_small_box")==null?"":b.getString("empty_small_box"));
        esb.setValue("0");
        esb.setHint("个                            ");
        list.add(esb);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean fbb = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        fbb.setName("大号重箱");
//        fbb.setValue(b.getString("full_big_box")==null?"":b.getString("full_big_box"));
        fbb.setValue("0");
        fbb.setHint("个                            ");
        list.add(fbb);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean fsb = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        fsb.setName("小号重箱");
//        fsb.setValue(b.getString("full_small_box")==null?"":b.getString("full_small_box"));
        fsb.setValue("0");
        fsb.setHint("个                            ");
        list.add(fsb);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean weight = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        weight.setName("去箱重量");
        list.add(weight);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean zl = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        zl.setName("总重量");
        list.add(zl);
        TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean bc = new TrasportBean.ArrayBean.CustomerAryBean.NeedWeightBean();
        bc.setName("联单号");
        list.add(bc);
        View foot = View.inflate(RecordweightActivity2.this, R.layout.record_weight_footview, null);
        View clear = foot.findViewById(R.id.clear);
        View readWeight = foot.findViewById(R.id.read_weight);
        View minusBox = foot.findViewById(R.id.minus_box);
        minusBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                readWeightValue += hdModelData.getWeight();

                String weight = allWeightEt.getText().toString();

                if (!weight.equals("")) {
                    float weightF = Float.valueOf(weight);
                    EditText bigNullBoxEdit = (EditText) mAboutQuestionListView.getChildAt(2).findViewById(R.id.record_value);
                    EditText smallNullBoxEdit = (EditText) mAboutQuestionListView.getChildAt(3).findViewById(R.id.record_value);
                    EditText bigfullBoxEdit = (EditText) mAboutQuestionListView.getChildAt(4).findViewById(R.id.record_value);
                    EditText smallfullBoxEdit = (EditText) mAboutQuestionListView.getChildAt(5).findViewById(R.id.record_value);
                    if (Utils.isNumeric(bigNullBoxEdit.getText().toString()) &&
                            Utils.isNumeric(smallNullBoxEdit.getText().toString()) &&
                            Utils.isNumeric(bigfullBoxEdit.getText().toString()) &&
                            Utils.isNumeric(smallfullBoxEdit.getText().toString())) {

                        float BoxWeight = (Float.valueOf(bigNullBoxEdit.getText().toString()) * Const.BIG_BOX_WEIGHT) + (Float.valueOf(smallNullBoxEdit.getText().toString()) * Const.SMALL_BOX_WEIGHT)
                                + (Float.valueOf(bigfullBoxEdit.getText().toString()) * Const.BIG_BOX_WEIGHT) + (Float.valueOf(smallfullBoxEdit.getText().toString()) * Const.SMALL_BOX_WEIGHT);
                        //                    weightF
                        weightF = weightF - BoxWeight;

                        noBoxWeightEt.setText(formartKeepStr(3, weightF));

                    } else {
                        Toast.makeText(RecordweightActivity2.this, "请输入正确箱子个数！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(RecordweightActivity2.this, "请输入总重量！", Toast.LENGTH_SHORT).show();
                }
                ;

            }
        });
        BleBus.getDefault().setOnClearZeroFinish(new BleBus.OnClearFinish() {
            @Override
            public void clearFinish(final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RecordweightActivity2.this, "数据已清零", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CheckBlueTooth() == false) {
                    new MsgAlert().show("请连接蓝牙设备");
                    startActivity(DeviceScanActivity.class);
                    return;
                }
                ;
                BluetoothService instance = BluetoothService.getInstance();

                instance.clearZero();
            }
        });
        BleBus.getDefault().setOnReadWeightSuccess(new BleBus.OnReceiveMsg() {
            @Override
            public void doRevMsg(HDModelData hdModelData) {
                String weight = allWeightEt.getText().toString().trim();

                if (!Utils.isNumeric(weight)) {
                    Toast.makeText(RecordweightActivity2.this, "输入框内必须为数字类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                float weightF = Float.valueOf(weight) + hdModelData.getWeight();

                Toast.makeText(RecordweightActivity2.this, "当前读取重量为：" + hdModelData.getWeight() + ",累加重量为" + weightF, Toast.LENGTH_SHORT).show();
                if (weightF <= 0) {
                    allWeightEt.setText(0 + "");
                } else {
                    allWeightEt.setText(formartKeepStr(3, weightF));
                }
            }
        });
        readWeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (CheckBlueTooth() == false) {
                    new MsgAlert().show("请连接蓝牙设备");
                    startActivity(DeviceScanActivity.class);
                    return;
                }
                ;
                BluetoothService instance = BluetoothService.getInstance();
                instance.readWeight();
            }
        });
        mAboutQuestionListView.addFooterView(foot);
        mAboutQuestionAdapter = new RecorWeightAdapter(this, list, R.layout.item_about_question);
        mAboutQuestionListView.setAdapter(mAboutQuestionAdapter);


        canmlTools = new CanmlTools(mContext, this);
        up_img.setOnClickListener(this);
        record_save.setOnClickListener(this);
        mAboutQuestionListView.post(new Runnable() {
            @Override
            public void run() {
                setAllWeight();
            }
        });
    }

    public boolean CheckBlueTooth() {
        if (BluetoothService.getInstance().getState() != BluetoothGatt.STATE_CONNECTED) {
            return false;
        }
        return true;
    }

    private void setAllWeight() {
        //设置输入控件
     /*   for (int i = 0; i < list.size() - 1; i++) {
            EditText view = (EditText)mAboutQuestionListView.getChildAt(i).findViewById(R.id.record_value);
            view.setFilters(new InputFilter[]{new DecimalInputFilter()});
        }*/
        noBoxWeightEt = (EditText) mAboutQuestionListView.getChildAt(6).findViewById(R.id.record_value);
        allWeightEt = (EditText) mAboutQuestionListView.getChildAt(7).findViewById(R.id.record_value);
        //TODO
    }

    boolean isALlPut;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.up_img:
                canmlTools.showCanmel(v.getId(), 0);

                break;
            case R.id.record_save:
                EditText saveEditText;
                for (int i = 0; i < list.size() - 1; i++) {
                    Log.i(TAG, "onClick: list" + list.size());
                    saveEditText = (EditText) mAboutQuestionListView.getChildAt(i).findViewById(R.id.record_value);
                    if (TextUtils.isEmpty(saveEditText.getText().toString())) {
                        new MsgAlert().show("请填写重量");
                        break;
                    } else {
                        if (i == list.size() - 2) {
                            isALlPut = true;
                        }
                    }
                }
                if (Utils.isNumeric(allWeightEt.getText().toString())) {
                    if (Float.valueOf(allWeightEt.getText().toString()) > 8000) {
                        Toast.makeText(RecordweightActivity2.this, "数值过大！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    Toast.makeText(RecordweightActivity2.this, "请输入正确数字！", Toast.LENGTH_SHORT).show();
                }

//                editText = (EditText) mAboutQuestionListView.getChildAt(list.size()-1).findViewById(R.id.record_value);

                saveEditText = (EditText) mAboutQuestionListView.getChildAt(list.size() - 1).findViewById(R.id.record_value);
                if (TextUtils.isEmpty(saveEditText.getText().toString())) {
                    new MsgAlert().show("请填写联单号");
                    break;
                }
//                ID = "idfjcsdjfadjfisajiidjiadij";
                if (TextUtils.isEmpty(ID)) {
                    new MsgAlert().show("请上传联单照片");
                    break;
                }

                if (isALlPut) {//请求接口
                    for (int i = 0; i < list.size() - 1; i++) {
                        saveEditText = (EditText) mAboutQuestionListView.getChildAt(i).findViewById(R.id.record_value);
                        if (i < 2) {
                            try {
                                fileParams.put(list.get(i).getWeightType(), formartKeepStr(3, Float.parseFloat(saveEditText.getText().toString())));
                            } catch (NumberFormatException e) {
                                fileParams.put(list.get(i).getWeightType(), formartKeepStr(3, 0.0f));
                                e.printStackTrace();
                            }
                        } else {
                            allWeight = saveEditText.getText().toString();
                        }
                    }
                    checkVehicle();
                }

                break;
            default:
                break;
        }
    }

    @Override
    public void camerPickphoto(String imageUri, int i) {
        Log.d("TransportfActivity", "" + imageUri);
        Bitmap tempbBitmap = ImageTools.bitmapFromPath(imageUri,
                (int) ImageTools.getDensity() * 65,
                (int) ImageTools.getDensity() * 65);

        switch (i) {
            case R.id.up_img:
                show_img.setImageDrawable(new BitmapDrawable(
                        getResources(), tempbBitmap));
                if (!DeviceUtil.isNetworkAvailable()) {
                    try {
                        ID = encodeBase64File(imageUri).replaceAll("[\\s*\t\n\r]", "");
                        Log.d("TransportfActivity", "" + ID);
                        NAME = imageUri;
                    } catch (Exception e) {
                        new MsgAlert().show("转换base64异常");
                        e.printStackTrace();
                    }

                } else {

                    //                fileArry.add(imageUri);
                    //                upArry[0].file = imageUri;

                    //                upLoadImage(imageUri, new ApplyRegistActivity.HttpCall(0));
                    Map<String, File> fileParams = new HashMap<>();
                    File file = new File(imageUri);
                    fileParams.put("file", file);
                    ServerControl sc = new ServerControl(fileParams);
                    sc.serverListener = new ServerControl.ServerListener() {
                        @Override
                        public void serverFinish(ServerResult sr) {
                            if (sr.isContinue) {
                                ID = sr.bodyData.optString("message");
                                new MsgAlert().show("上传成功，请保存提交");
                            }
                        }
                    };
                    new ProgressDialog(mContext).startControlUPpic(sc);

                }
                break;
            default:
                break;

        }
    }

    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        canmlTools.onresult(requestCode, data);
    }


    private void checkVehicle() {

        EditText editText = (EditText) mAboutQuestionListView.getChildAt(list.size() - 1).findViewById(R.id.record_value);//联动号码输入的内容
        ArrayList<String> mL = new ArrayList<>();
        ArrayList<String> photo_names = new ArrayList<>();
        photo_names.add(NAME);
        ArrayList<Map<String, String>> needWeight = new ArrayList<>();
        needWeight.add(fileParams);
        int nullBoxWeight = SetData.getNullBoxWeight();
        int fullBoxWeight = SetData.getFullBoxWeight();
//        float boxUnInstallWeight = SetData.getBoxUnInstallWeight();
        float boxInstallWeight = SetData.getBoxInstallWeight();
//        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
        allWeight = RecordweightActivity2.this.allWeightEt.getText().toString();

        String weight = "0";
        //空箱重量
        float noBoxWeight = Float.parseFloat(noBoxWeightEt.getText().toString());
        if (noBoxWeight <= 0) {
            weight = formartKeepStr(3, Float.parseFloat(allWeight));
        } else {
            weight = formartKeepStr(3, noBoxWeight);
        }
        if (ID.length() > 50) {
            mL.add("");
            GetRecord getRecord = new GetRecord(c.getId(), editText.getText().toString(), weight, mL, needWeight, photo_names);
            getRecord.emptyweight = formartKeepStr(3, nullBoxWeight * 1.0f);
            getRecord.fullweight = formartKeepStr(3, fullBoxWeight * 1.0f);
            getRecord.boxweight = formartKeepStr(3, boxInstallWeight);
            RequeastBean bean = new RequeastBean("save", "com.cygps.dubbo.WasteTransport.IInputKg", getRecord);
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);

            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetRecord.class.getName());
            requestPersistent.setType("2");
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //保存缓存后清除重量缓存
            clearWeight();
            String id = c.getId();
            Intent i = new Intent(mContext, NameActivity.class);
            i.putExtra("id", id);
            mContext.startActivity(i);
        } else {
            mL.add(ID);
            GetRecord getRecord = new GetRecord(c.getId(), editText.getText().toString(), weight, mL, needWeight);
            getRecord.emptyweight = formartKeepStr(3, nullBoxWeight * 1.0f);
            getRecord.fullweight = formartKeepStr(3, fullBoxWeight * 1.0f);
            getRecord.boxweight = formartKeepStr(3, boxInstallWeight);
            RequeastBean bean = new RequeastBean("save",
                    "com.cygps.dubbo.WasteTransport.IInputKg", getRecord);
            ServerControl sc = new ServerControl(bean);

            msgSp = "\n收运提交:" + TextUtil.getCurTime()
                    + "\nUrl:" + sc.getUrl() + "\n参数:" + getRecord.toString();
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        //提交成功清除重量缓存
                        clearWeight();
                        String id = c.getId();
                        Intent i = new Intent(mContext, NameActivity.class);
                        i.putExtra("id", id);
                        mContext.startActivity(i);
                    }

                    //保存到sp
                    msgSp = msgSp + "\n\n收运提交返回:" + TextUtil.getCurTime() +
                            "\n" + sr.toString() +
                            "\n-----------------------------------------------------------\n"
                            + sp.getString(TextUtil.commitKey, "");
                    sp.edit().putString(TextUtil.commitKey, msgSp).commit();
                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }

    private void clearWeight() {
        SetData.setFullBoxWeight(0);
        SetData.setNullBoxWeight(0);
//        SetData.setBoxUnInstallWeight(0);
        SetData.setBoxInstallWeight(0f);
    }

    public static String formartKeepStr(int keepNum, float sdata) {
        return String.format("%." + keepNum + "f", sdata);
    }
}
